<template>
  <div class="rolesContain">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-button type="primary" @click="dialogVisibleAddRoles = true"
          >添加角色</el-button
        >
      </el-row>
      <el-table :data="rolesData" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="[index == 0 ? 'borderTop' : '', 'borderBottom']"
            >
              <!-- 一级标签栏 -->
              <el-col :span="5">
                <el-tag closable @close="handClose(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级标签栏 -->
              <el-col :span="19">
                <el-row
                  v-for="(item1, index1) in item.children"
                  :key="item1.id"
                  :class="index1 == 0 ? '' : 'borderTop'"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="handClose(scope.row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      type="warning"
                      closable
                      @close="handClose(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色用户的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogVisibleAddRoles"
      @close="resetFormAddrole"
    >
      <el-form :model="ruleFormAddRoles" :rules="rulesRoles" ref="addRolesForm">
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="ruleFormAddRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
          <el-input v-model="ruleFormAddRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAddRoles = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="dialogVisibleEditRoles"
      @close="resetFormEditrole"
    >
      <el-form
        :model="ruleFormEditRoles"
        :rules="rulesRoles"
        ref="editRolesForm"
      >
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="ruleFormEditRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
          <el-input v-model="ruleFormEditRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEditRoles = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisibleSetting"
      @close="setRightDialogClose"
    >
      <el-tree
        :data="settingTree"
        show-checkbox
        :props="propsTree"
        default-expand-all
        :default-checked-keys="defKeys"
        node-key="id"
        ref="refTree"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleSetting = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getRolesList()
  },
  data() {
    return {
      // 保存角色列表的数据
      rolesData: [],
      // 添加角色的对话框是否显示
      dialogVisibleAddRoles: false,
      // 添加角色表单数据
      ruleFormAddRoles: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色的表单验证
      rulesRoles: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 编辑角色的数据
      ruleFormEditRoles: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色的id
      editRoleId: '',
      // 编辑角色对话框是否显示
      dialogVisibleEditRoles: false,
      // 分配权限对话框是否显示
      dialogVisibleSetting: false,
      // 获取权限的数据
      settingTree: [],
      // 树形控件的属性绑定对象
      propsTree: {
        // 通过label设置树形节点文本展示authName
        label: 'authName',
        // 设置通过children属性展示子节点信息
        children: 'children'
      },
      // 默认勾选节点的数组
      defKeys: [],
      // 选中角色id
      roleId: ''
    }
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesData = res.data
    },
    // 添加角色
    addRoles() {
      this.$refs.addRolesForm.validate(async valid => {
        if (!valid) {
          return this.$message.error('输入的信息不符合规范')
        }
        const { data: res } = await this.$http.post(
          'roles',
          this.ruleFormAddRoles
        )
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('创建角色失败')
        }
        this.$message.success(res.meta.msg)
        this.dialogVisibleAddRoles = false
        this.getRolesList()
      })
    },
    // 关闭添加角色对话框时重置表单
    resetFormAddrole() {
      this.$refs.addRolesForm.resetFields()
    },
    // 显示编辑角色列表对话框
    async showEditDialog(roleId) {
      this.dialogVisibleEditRoles = true
      // console.log(roleId)
      // 查询角色并显示在编辑对话框中
      const { data: res } = await this.$http.get('roles/' + roleId)
      // console.log(res)
      this.ruleFormEditRoles = res.data
      this.editRoleId = res.data.roleId
    },
    // 编辑角色列表
    editRoles() {
      this.$refs.editRolesForm.validate(async valid => {
        // console.log(valid)
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleId,
          this.ruleFormEditRoles
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }
        this.$message.success('编辑角色成功')
        this.dialogVisibleEditRoles = false
        this.getRolesList()
      })
    },
    // 关闭编辑角色对话框时重置表单
    resetFormEditrole() {
      this.$refs.editRolesForm.resetFields()
    },
    // 删除角色
    async deleteRoles(roleId) {
      const { data: res } = await this.$http.delete('roles/' + roleId)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    // 删除角色指定权限
    async handClose(role, id) {
      console.log(role, id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${id}`
          )
          // console.log(res)
          role.children = res.data
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配权限对话框是否显示和获取权限列表数据
    async showSetRightDialog(row) {
      this.dialogVisibleSetting = true
      console.log(row)
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.settingTree = res.data
      this.roleId = row.id
      this.getLeafKeys(row, this.defKeys)
    },
    // 递归方法勾选默认的第三级权限
    getLeafKeys(node, arr) {
      // 该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      // 如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 关闭分配权限对话框,清楚默认勾选的数组
    setRightDialogClose() {
      this.defKeys = []
    },
    // 设置角色的权限
    async allotRights() {
      // tree中被选中id的数组
      const checkedArr = this.$refs.refTree.getCheckedKeys()
      // console.log(checkedArr)
      // tree中半选中的id组成的数组
      const halfCheckedArr = this.$refs.refTree.getHalfCheckedKeys()
      // console.log(halfCheckedArr)
      const arr = [...checkedArr, ...halfCheckedArr]
      const arrStr = arr.join(',')
      // console.log(arrStr)
      // console.log(arr)
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: arrStr
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('分配权限成功')
      this.dialogVisibleSetting = false
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.borderTop {
  border-top: 1px solid #eee;
}
.borderBottom {
  border-bottom: 1px solid #eee;
}
.el-row {
  display: flex;
  align-items: center;
  margin-bottom: 0;
}
.el-tag {
  margin: 7px;
}
</style>
